import {
  selectAllMenu,
  selectAllMenuId,
  addMenu,
  updateMenu,
  deleteMenu
} from '@/api/menu'

const getDefaultState = () => {
  return {
    menus: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // user select all menu
  selectAllMenu({
    commit
  }, menuInfo) {
    return new Promise((resolve, reject) => {
      const {
        obj,
        page,
        pageSize
      } = menuInfo
      selectAllMenu({
        obj: obj,
        page: page,
        pageSize: pageSize
      }).then(response => {
        resolve(response.data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // use select all menuId
  selectAllMenuId({
    commit
  }, menuInfo) {
    return new Promise((resolve, reject) => {
      const {
        obj,
        page,
        pageSize
      } = menuInfo
      selectAllMenuId({
        obj: obj,
        page: page,
        pageSize: pageSize
      }).then(response => {
        resolve(response.data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // use add menu
  addMenu({
    commit
  }, menuInfo) {
    return new Promise((resolve, reject) => {
      const {
        name,
        title,
        path,
        icon,
        component,
        parentId,
        isOpen
      } = menuInfo
      addMenu({
        name: name,
        title: title,
        path: path,
        icon: icon,
        component: component,
        parentId: parentId,
        isOpen: isOpen
      }).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // use update menu
  updateMenu({
    commit
  }, menuInfo) {
    return new Promise((resolve, reject) => {
      const {
        menuId,
        name,
        title,
        path,
        icon,
        component,
        parentId,
        isOpen
      } = menuInfo
      updateMenu({
        menuId: menuId,
        name: name,
        title: title,
        path: path,
        icon: icon,
        component: component,
        parentId: parentId,
        isOpen: isOpen
      }).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // use delete menu
  deleteMenu({
    commit
  }, ids) {
    return new Promise((resolve, reject) => {
      deleteMenu(ids).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
